package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.zzyl.common.utils.Thread.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.ReservationDto;
import com.zzyl.nursing.mapper.MemberReservationMapper;
import com.zzyl.nursing.service.IMemberReservationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class MemberReservationServiceImpl implements IMemberReservationService {

    @Autowired
    private MemberReservationMapper memberReservationMapper;
    /**
     * 获取用户预约的取消数量
     * @param userId
     * @return
     */
    @Override
    public Integer selectReservationCountByDay(Long userId) {
        // 获取用户预约的取消数量
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        Integer count = memberReservationMapper.selectReservationCountByDay(userId, startTime, endTime);
        return count == null ? 0 : count;
    }

    /**
     * 获取用户每个时间段剩余预约次数
     * @param time
     * @return
     */
    @Override
    public List<Map<String,Object>> selectReservationCountByTime(Long time) {
        Long userId = UserThreadLocal.getUserId();
        long dataTime = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(dataTime);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        List<Map<String, Object>> list = memberReservationMapper.selectReservationCountByTime(userId, time, startTime, endTime);
        return list;
    }

    /**
     * 添加预约
     * @param dto
     * @return
     */
    @Override
    public int insertReservation(ReservationDto dto) {
        Reservation reservation = new Reservation();
        BeanUtil.copyProperties(dto, reservation);
        reservation.setStatus(0);
        reservation.setCreate_time(LocalDateTime.now());
        reservation.setUpdate_time(LocalDateTime.now());
        reservation.setCreate_by(UserThreadLocal.getUserId());
        reservation.setUpdate_by(UserThreadLocal.getUserId());

        int i = memberReservationMapper.insertReservation(reservation);
        return i;
    }
}
